package com.soulless.demo.dynamicproxy.soullessproxy.proxy;

import java.lang.reflect.Method;

/**
 * @author zenglei
 * @Description 功能描述
 * @date 2022/11/23 15:38
 */
public class SoullessProxy {

    public static final String ln = "\r\n";

    public static Object newProxyInstance(SoullessClassLoader loader,
                                          Class<?>[] interfaces,
                                          SoullessInvocationHandler h) {

        /**
         * 1、动态生成源码.java文件
         */
        String src = generateSrc(interfaces);
        /**
         * 2、java文件输出到磁盘，保存为文件$Proxy0.java
         */

        /**
         * 3、把.java文件编译成$Proxy0.class文件
         */

        /**
         * 4、把生成的.class文件加载到jvm中
         */

        /**
         * 5、返回新的代理对象
         */
        return null;
    }

    private static String generateSrc(Class<?>[] interfaces) {
        StringBuffer sb = new StringBuffer();
        sb.append("com.soulless.demo.dynamicproxy.soullessproxy.proxy.SoullessProxy" + ln);
        sb.append("import com.soulless.demo.dynamicproxy.soullessproxy.client.IPerson" + ln);
        sb.append("import java.lang.reflect.*" + ln);
        sb.append("public final class $Proxy0 implements " + interfaces[0].getName() + " {" + ln);
        sb.append("SoullessInvocationHandler h" + ln);
        sb.append("public $Proxy0(SoullessInvocationHandler h) {" + ln);
        sb.append("this.h = h;" + ln);
        sb.append("}" + ln);

        for (Method m: interfaces[0].getMethods()) {
            Class<?>[] params = m.getParameterTypes();
            StringBuilder paramNames = new StringBuilder();
            StringBuilder paramValues = new StringBuilder();
            StringBuilder paramClasses = new StringBuilder();

            for (int i = 0; i < params.length; i++) {
                Class clazz = params[i];
                String type = clazz.getName();


            }

            sb.append("" + m.getReturnType().getName() + " " + m.getName() + "() {" + ln);
            sb.append("try {" + ln);

            sb.append("} catch (Error _ex) {}" + ln);
            sb.append("catch(Throwable throwable) {" + ln);
            sb.append("throw new UndeclaredThrowableException(throwable);" + ln);
            sb.append("}");

            sb.append("}");

        }

        sb.append("}");

        return sb.toString();
    }

}
